package com.wyvoid.core.persistent.hibernate;

import com.wyvoid.core.util.ResolverUtil;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

import javax.persistence.Entity;
import java.util.Set;

/**
 * 在用hibernate annotation 做orm时,spring AnnotationSessionFactoryBean没有提供方便的装载一个包或目录下的所有hibernate entity<br>
 * 此类正是为了补充Spring AnnotationSessionFactoryBean的不足<br>
 * 用法如下：
 * <pre>
 *
 *  <bean id="sessionFactory" class="com.wyvoid.core.persistent.hibernate.PackageAnnotationSessionFactoryBean">
 *       <property name="dataSource" ref="dataSource"/>
 *       <property name="annotatedPackage">
 *           <list>
 *               <value>com.wyvoid.forum.domain</value>
 *           </list>
 *      </property>
 *   </bean>
 * 这样就会把com.wyvoid.forum.domain下声明了@Entity的所有Class都装载成Hibernate Entity
 * </pre>
 * <p>51void.com</p>
 *
 * User:cjp
 * Date: 2007-5-12
 * Time: 15:49:22
 */
public class PackageAnnotationSessionFactoryBean extends AnnotationSessionFactoryBean {
    private String[] annotatedPackage;


    public void setAnnotatedPackage(String[] annotatedPackage) {
        this.annotatedPackage = annotatedPackage;

        ResolverUtil<Entity> resolver = new ResolverUtil<Entity>();

        resolver.findAnnotated(Entity.class,annotatedPackage);//查找所有声明了@Entity的Class
        Set<Class<? extends Entity>> beans = resolver.getClasses();

        Class[] classA=new Class[beans.size()];
        beans.toArray(classA);
        super.setAnnotatedClasses(classA);//调用Spring中AnnotationSessionFactoryBean的setAnnotatedClasses方法，将所有Entity注入
    }


    public String[] getAnnotatedPackage() {
        return annotatedPackage;
    }
}
